﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Audio;

namespace BNB7.Entry
{
    public enum SoundName
    {
        snBG = 0,
        snStart,
        snLay,
        snExplode,
        snAppear,
        snGet,
        snDie,
        snWin,
        snDraw,
        snSave
    };

    public class Sound
    {
        const int SOUND_NUM = 10;
        const string SOUND_DIR = "Snd";
        static readonly string[] szFileSound = new string[SOUND_NUM]
	    {
		    "bg",
		    "start",
		    "lay",
		    "explode",
		    "appear",
		    "get",		
		    "die",
		    "win",
		    "draw",
		    "save"
	    };

        private SoundEffectInstance[] m_vSound;

        /// <summary>
        /// 是否打开背景音乐
        /// </summary>
        public bool IsOpenMusic
        {
            get;
            set;
        }

        /// <summary>
        /// 是否打开音效
        /// </summary>
        public bool IsOpenEffect
        {
            get;
            set;
        }

        #region --- 单例实现 ---

        private static Sound instance = null;
        private static readonly object locker = new object();

        public static Sound Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (locker)
                    {
                        if (instance == null)
                        {
                            instance = new Sound();
                        }
                    }
                }

                return instance;
            }
        }

        #endregion

        public void Init()
        {
            IsOpenMusic = true;
            IsOpenEffect = true;

            m_vSound = new SoundEffectInstance[SOUND_NUM];

            // 加载音效
            for (int i = 0; i < SOUND_NUM; ++i)
            {
                m_vSound[i] = BNB7Game.Instance.Content.Load<SoundEffect>(SOUND_DIR + "\\" + szFileSound[i]).CreateInstance();
            }
        }

        public void Play(SoundName sn)
        {
            bool isPlay = false;
            if (sn == SoundName.snBG)
            {
                isPlay = IsOpenMusic;
            }
            else
            {
                isPlay = IsOpenEffect;
            }

            if (isPlay)
            {
                m_vSound[(int)sn].Play();
            }
        }

        public void StopMusic()
        {
            m_vSound[(int)SoundName.snBG].Stop();
        }

        public void Update(float fDelta)
        {
            if (IsOpenMusic && m_vSound[(int)SoundName.snBG].State == SoundState.Stopped)
            {
                m_vSound[(int)SoundName.snBG].Resume();
            }
        }
    }
}
